package main;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;

public class CommandDb {
	
	
	public void add(Workers m) throws Exception {
		ReflectionQuery rq = new ReflectionQuery();
		try(DBWorker _dbWorker = new DBWorker()) {
			_dbWorker.connectDB();
			_dbWorker.executeVoid(rq.getAddQuery(m));
		}catch(Exception e) {
			System.out.println("Error: "+e.toString());
		}
	}
	
	public void update(Workers m) {
		try(DBWorker _dbWorker = new DBWorker()) {
			_dbWorker.connectDB();
			_dbWorker.executeVoid("UPDATE workers SET Name ='" + m.get_name() 
					+ "', Surname='" + m.get_surname() + "', age=" 
					+ m.getAge() + ", salary=" + m.getSalary()
					+ " WHERE id=" + m.getId());
		}catch(Exception e) {
			System.out.println("Error: "+e.toString());
		}
	}
	
	public void delete(int id) {
		try(DBWorker _dbWorker = new DBWorker()) {
			_dbWorker.connectDB();
			_dbWorker.executeVoid("DELETE FROM workers WHERE id = "+id);
		}catch(Exception e) {
			System.out.println("Error: "+e.toString());
		}
	}
	
	public LinkedList<Workers> getAll() {
		LinkedList<Workers> men = new LinkedList<Workers>();
		try(DBWorker _dbWorker = new DBWorker()){
			_dbWorker.connectDB();
			ResultSet rs = _dbWorker.execute("select * from workers");
			if (rs != null)
				while (rs.next()) {
					Workers newMan = new Workers();
					newMan.set_name(rs.getString("Name"));
					newMan.set_surname(rs.getString("surname"));
					newMan.setAge(Integer.valueOf(rs.getString("Age")));
					newMan.setSalary(Integer.valueOf(rs.getString("Salary")));
					newMan.setId(Integer.valueOf(rs.getString("ID")));
					men.add(newMan);
				}
		} catch (SQLException e) {
			System.out.println("Error: " + e.toString());
		}
		return men;
	}
}
